﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;

/// <summary>
/// This module is used to intercept the requests to ASNet and to redirect to the best available SSAS instance URL
/// </summary>
public class ModuleRedirector : IHttpModule
{
    public void Dispose() {}

    public void Init(HttpApplication context)
    {
        context.PostAuthorizeRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;

        //pull application properties which we later use for determining the ASNet session handle
        string IPAddress = app.Request.UserHostAddress.ToString();
        string userName = app.User.Identity.Name.ToString();
        string key = app.Request.AppRelativeCurrentExecutionFilePath.ToLower().Substring(2).TrimEnd('/');
        string parameters = "";
        bool useSessions = true;

        //construct the params string and make sure UseSessions parameter works
        NameValueCollection nvc = app.Request.QueryString;
        foreach(string k in nvc.AllKeys) {
            parameters += k + nvc[k];
            if (k.ToLower() == "usesessions" && nvc[k].ToLower() == "false")
            {
                useSessions = false;
            }
        }

        //this retrieves the URL to which we will be redirecting. if there is an existing session we just return the same
        //URL as before. otherwise we create a new one and returns its URL; unless we don't use sessions and then we just
        //get the next available URL without accessing the sessions cache
        string URL = null;
        if (useSessions)
        {
            URL = (new ASNet()).getURL(IPAddress, userName, key, parameters);
        }
        else
        {
            URL = (new ASNet()).getURL();
        }

        if (URL == null)
        {
            // No redirect found, send ~/default.htm
            app.Response.StatusCode = 404;
            app.Response.StatusDescription = "Object Not Found";
            app.Response.WriteFile(app.Server.MapPath("~/default.htm"));
        }
        else
        {
            //Begin Response
            app.Response.StatusCode = 307;
            app.Response.StatusDescription = "Temporary Redirect";
            string ResponseBody = "<html><head><title>{2} {3}</title></head><body><h1>{2} {3}</h1><p>See <a href=\"{0}\">{0}</a></p></body></html>";

            app.Response.AppendHeader("Location", URL);
            app.Response.Output.Write(ResponseBody,
                URL,
                app.Request.Url,
                app.Response.StatusCode,
                app.Response.StatusDescription);

            app.CompleteRequest();
        }
    }
}